﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eqwww.Code;
using Eqwww.Data;
using Eqwww.Domain;
using Eqwww.Domain.Models.SystemSecurity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace Eqwww.App.SystemSecurity
{
    public class VersionLogApp
    {
        private ApplicationDbContext _context;
        private IModelHandler _modelHandler;
        private IConfiguration _configuration;
        public VersionLogApp(ApplicationDbContext context, IModelHandler modelHandler
            , IConfiguration configuration)
        {
            _context = context;
            _modelHandler = modelHandler;
            _configuration = configuration;
        }

        public IQueryable<VersionLogModel> FindIQueryable(Pagination pagination)
        {
            var exp = ExtLinq.True<VersionLogModel>();
            exp = exp.And(x => x.DeleteMark != true);
            var data = _context.FindQueryable(exp, pagination).Include(x => x.CreateUser).Include(x => x.LastUpdateUser);
            return data;
        }

        public VersionLogModel Find(string id)
        {
            var model = _context.Set<VersionLogModel>().AsNoTracking().FirstOrDefault(x => x.DeleteMark != true && x.Id == id);
            return model;
        }

        public VersionLogModel FindInclude(string id)
        {
            var model = _context.Set<VersionLogModel>().AsNoTracking()
                .Include(x=>x.CreateUser)
                .Include(x=>x.LastUpdateUser)
                .Include(x=>x.DeleteUser)
                .FirstOrDefault(x => x.DeleteMark != true && x.Id == id);
            return model;
        }

        public ModelResult Create(VersionLogModel model)
        {
            _modelHandler.Create(model);
            _context.Add(model);
            _context.SaveChanges();
            return Common.SuccessResult();
        }

        public async Task<ModelResult> UpdateAsync(VersionLogModel model)
        {
            _modelHandler.Update(model);
            _context.Update(model);
            await _context.SaveChangesAsync();
            return Common.SuccessResult();
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <returns></returns>
        public async Task<ModelResult> DeleteLogicAsync(VersionLogModel model)
        {
            _modelHandler.Delete(model);
            _context.Update(model);
            await _context.SaveChangesAsync();
            return Common.SuccessResult();
        }
    }
}
